<?php
require_once 'db.inc.php';

class Comments {
	private $link;
	public $blog_comments;
	public function __construct() {
		try {
			$this->link = new PDO(DB_INFO, DB_USERNAME, DB_PASSWORD);
		} catch (PDOException $e) {
			die("Cannot connect database:".$e->getMessage());
		}
	}
	public function show_comment_form($blog_id) {
		if (isset($_SESSION["comment_blog_id"]) &&
			$blog_id == $_SESSION["comment_blog_id"]) {
			$n = $_SESSION["comment_name"];
			$e = $_SESSION["comment_email"];
			$c = $_SESSION["comment"];
		} else {
			$e = $c = $n = NULL;
		}
		return <<<FORM
<form action="/SimpleBlog/inc/update.inc.php" method="POST" id="comment-form">
	<fieldset>
		<legend>发表评论</legend>
		<label>名字
			<input type="text" name="name" maxlength="150" value="$n" />
		</label>
		<label>Email
			<input type="text" name="email" maxlength="150" value="$e"/>
		</label>
		<label>评论
			<textarea rows="6" cols="10" name="comment">$c</textarea>
		</label>
		<input type="hidden" name="blog_id" value="$blog_id" />
		<input type="submit" name="submit" value="发表评论" />
		<input type="submit" name="submit" value="取消" />
	</fieldset>
</form>
FORM;
	}

	public function save_comment($post) {
		$bid = htmlentities($post["blog_id"]);
		$name = htmlentities($post["name"]);
		$email = htmlentities($post["email"]);
		$comment = htmlentities($post["comment"]);
		$comment = nl2br(trim($comment));
		// 保存到 SESSION，使下次自动出现
		$_SESSION["comment_blog_id"] = $bid;
		$_SESSION["comment_name"] = $name;
		$_SESSION["comment_email"] = $email;
		$_SESSION["comment"] = $comment;
		if (empty($name) || empty($email) || empty($comment) ||
			!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			return false;
		}
		$sql = "INSERT INTO comments (blog_id, name, email, comment)
				VALUES (?, ?, ?, ?)";
		$stmt = $this->link->prepare($sql);
		if ($stmt && $stmt->execute(array($bid, $name, $email, $comment))) {
			$stmt->closeCursor();
			unset($_SESSION["comment_blog_id"], $_SESSION["comment_name"],
					$_SESSION["comment_email"], $_SESSION["comment"]);
			return true;
		} else {
			return false;
		}
	}

	public function retrieve_comments($blog_id) {
		$sql = "SELECT id, name, email, comment, date FROM comments
				WHERE blog_id=? ORDER BY date DESC";
		$stmt = $this->link->prepare($sql);
		$this->blog_comments = array();
		if ($stmt && $stmt->execute(array($blog_id))) {
			foreach ($stmt as $row) {
				$this->blog_comments[] = $row;
			}
		}
		if (empty($this->blog_comments)) {
			$this->blog_comments[] = array(
				"id" 		=> NULL,
				"name" 		=> NULL,
				"email" 	=> NULL,
				"comment" 	=> NULL,
				"date" 		=> NULL
			);
		}
	}

	public function show_comments($blog_id) {
		$disp = NULL;
		$this->retrieve_comments($blog_id);
		foreach ($this->blog_comments as $c) {
			if (!empty($c["date"]) && !empty($c["name"])) {
				$format = "F j, Y \a\\t g:iA";
				$date = date($format, strtotime($c["date"]));
				$byline = "<span><strong>$c[name]</strong>
                            [发表于 $date]</span>";
				if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] == 1) {
					$admin = "<a href=\"/SimpleBlog/inc/update.inc.php"
							."?action=comment_delete&id=$c[id]\""
							. "class=\"admin\">删除</a>";
				} else {
					$admin = NULL;
				}
				$disp .= "<p class=\"comment\">$byline$c[comment]$admin</p>";
			} else {
				$byline = NULL;
				$admin = NULL;
			}
		}
		if (!isset($disp)) {
			$disp = "该文章暂无评论。";
		}
		return $disp;
	}

	// 返回确认删除的表单
	public function confirm_delete($id) {
		if (isset($_SERVER["HTTP_REFERER"])) {
			$url = $_SERVER["HTTP_REFERER"];
		} else {
			$url = "/SimpleBlog/index.php";
		}
		return <<<FORM
<html>
<head>
<title>确认删除评论?</title>
<link rel="stylesheet" type="text/css"
    href="/SimpleBlog/css/default.css" />
</head>
<body>
<form action="/SimpleBlog/inc/update.inc.php" method="POST">
    <fieldset>
        <legend>请确认</legend>
        <p>
            	你确定要删除这条评论吗？
        </p>
        <input type="hidden" name="id" value="$id" />
        <input type="hidden" name="action" value="comment_delete" />
        <input type="hidden" name="url" value="$url" />
        <input type="submit" name="confirm" value="是" />
        <input type="submit" name="confirm" value="否" />
    </fieldset>
</form>
</body>
</html>
FORM;
	}
	public function delete_comment($id) {
		$sql = "DELETE FROM comments WHERE id=?";
		$stmt = $this->link->prepare($sql);
		if ($stmt && $stmt->execute(array($id))) {
			$stmt->closeCursor();
			return true;
		} else {
			return false;
		}
	}
}